﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SharedGenomics.Workbench.Views;
using SharedGenomics.Workbench.PresentationModel;
using SharedGenomics.Workbench.Models;
using SharedGenomics.Core;
using SharedGenomics.DataAccess;

namespace SharedGenomics.Workbench.Presenters
{
    public class WatchListPresenter : Presenter
    {
        public WatchListPresenter(IWatchListView view, WatchListModel model, IOpenFileDialogView openDialog, IMarkerWatchListParser watchListParser)
            : base(view)
        {
            //register for view events
            view.OpenWatchListClicked += new EventHandler(this.View_OpenWatchListClicked);
            view.SelectedItemChanged += new EventHandler(this.View_SelectedItemChanged);

            //set model on view
            view.Model = model;

            //set private members
            this.WatchListView = view;
            this.Model = model;
            this.OpenDialog = openDialog;
            this.WatchListParser = watchListParser;
        }

        public void SyncWith<T>(IEnumerable<T> data, Func<T, string> mapFunc)
        {
            this.Model.SyncWith<T>(data, mapFunc);
        }

        public IEnumerable<string> WatchList
        {
            get { return this.Model.Items.Select(wi => wi.Name); }
        }

        private void View_SelectedItemChanged(object sender, EventArgs e)
        {
            this.SelectedItemChanged.Raise(this);
        }

        private void View_OpenWatchListClicked(object sender, EventArgs e)
        {
            string fileName = this.OpenDialog.Open();
            if (fileName != null)
            {
                //parse snp names file, add to model and display in view
                var watchListItems = this.WatchListParser.Parse(fileName);
                this.Model.LoadIdentifiers(watchListItems);
                this.WatchListLoaded.Raise(this);
            }
        }

        private IWatchListView WatchListView { get; set; }
        private WatchListModel Model { get; set; }
        private IOpenFileDialogView OpenDialog { get; set; }
        private IMarkerWatchListParser WatchListParser { get; set; }

        public string SelectedItem
        {
            get
            {
                WatchListItem selected = this.WatchListView.SelectedItem;
                return selected == null
                    ? null
                    : selected.Name;
            }
        }

        public event EventHandler SelectedItemChanged;
        public event EventHandler WatchListLoaded;
    }
}
